

import IO

def writeProtocol(constArray, structArray, bodyArray, fileArray, nameArray):
    writeProtocolConst(constArray)
    writeProtocolStruct(structArray)
    writeProtocolStruct(bodyArray)
    writeProtocolListFilePy(nameArray)
    writeInitFile(fileArray)


def writeProtocolConst(array):
    index = 0
    writeStr = "# -*- coding: UTF-8 -*-\n"
    for constNode in array:
        formatStr = "{} = {} #{} \n"
        if index == len(array):
          formatStr = "{} = {} #{} \n"
        name = constNode.getAttribute("name")
        value = constNode.getAttribute("value")
        desc = constNode.getAttribute("desc").encode(encoding='UTF-8')
        value = formatStr.format(name, value, desc)
        writeStr = writeStr + value
        index += 1

    IO.outPutFile(IO.OUT_PUT_PATH + "ProtocolConst.py", writeStr)


def writeProtocolStruct(array):
    for structData in array:
        structName = structData.getAttribute("name")
        print structName
        headFormatStr = "class create:\n" \
              "   def __init__(self):\n"
        writeStr = ""
        headStr = headFormatStr.format("create")
        bodyList = []
        for structItem in structData.getElementsByTagName("item"):
            itemName = structItem.getAttribute("name")
            valueType = structItem.getAttribute("type")
            itemDesc = structItem.getAttribute("desc")
            defaultValue = None
            if valueType == "int":
                defaultValue = 0
            elif valueType == "string":
                defaultValue = "''"
            elif valueType == "array":
                defaultValue = "[]"
                bodyList.append(structItem.getAttribute("cell"))
            else:
                defaultValue = "{}.create()".format(valueType)
                bodyList.append(valueType)
            headFormatStr = "         self.{} = {}   \n".format(itemName, defaultValue, itemDesc)
            headStr = headStr + headFormatStr
        # write encode
        encodeStr = "   def encode(self,buff):\n"
        for structItem in structData.getElementsByTagName("item"):
            valueStr = "        buff.write{}(self.{})\n"
            valueName = structItem.getAttribute("name")
            valueType = structItem.getAttribute("type")
            if valueType == "int" or valueType == "string":
                valueStr = valueStr.format(valueType.capitalize(), valueName)
            else:
                valueStr = "        self.{}.encode(buff)\n".format(valueName)
            encodeStr = encodeStr + valueStr
        # write decode
        decodeStr = "   def decode(self,buff):\n"
        for structItem in structData.getElementsByTagName("item"):
            valueStr = "        self.{} = buff.read{}()\n"
            valueName = structItem.getAttribute("name")
            valueType = structItem.getAttribute("type")
            if valueType == "int":
                valueStr = "        self.{} = buff.readInt()\n".format(valueName)
            elif valueType == "string":
                valueStr = "        self.{} = buff.readString()\n".format(valueName)
            elif valueType == "array":
                countName = "{}Count".format(valueName)
                cellValue = structItem.getAttribute("cell")
                valueStr = "        {} = buff.readInt()\n".format(countName)
                valueStr = valueStr + "        self.{} = []\n".format(valueName)
                valueStr = valueStr + "        for num in range(0,{}):\n".format(countName)
                valueStr = valueStr + "             {}Cell = {}.create()\n".format(cellValue,cellValue)
                valueStr = valueStr + "             {}Cell.decode(buff)\n".format(cellValue, cellValue)
                valueStr = valueStr + "             self.{}.append({}Cell)\n".format(valueName, cellValue)
            else:
                valueStr = "        self.{} = {}.create()\n".format(valueName, valueType)
                valueStr = valueStr + "        self.{}.decode(buff)".format(valueName)
            decodeStr = decodeStr + valueStr

        if len(bodyList) > 0:
            bodyImportStr = ""
            for bodyName in bodyList:
                bodyImportStr = "import {} \n".format(bodyName)
            writeStr = bodyImportStr + headStr + encodeStr + decodeStr
        else:
            writeStr = headStr + encodeStr + decodeStr
        IO.outPutFile(IO.OUT_PUT_PATH + structName + ".py", writeStr)


def writeProtocolListFilePy(array):
    content = "import ProtocolConst \nMsgs = {}\n"
    for protocol in array:
        msgName = protocol.getAttribute("name")
        cellContent = "Msgs[{}] = '{}'\n"
        cellContent = cellContent.format("ProtocolConst." + msgName,msgName)
        content = content + cellContent
        IO.outPutFile(IO.OUT_PUT_PATH + "Protocols.py", content)


def writeInitFile(array):
    # write __init_py
    writeStr = '__all__ = ['
    index = 0
    for pyModule in array:
        if index != len(array) - 1:
            writeStr = writeStr + '"' + pyModule + '",\n'
        else:
            writeStr = writeStr + '"' + pyModule + '"' + ']'
        index = index + 1
    IO.outPutFile(IO.OUT_PUT_PATH + "__init__.py", writeStr)
